package com.luyuan.crm.member.web;

import java.util.List;

import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberIntegralReceived;
import com.luyuan.crm.member.service.MemberIntegralReceivedService;
import com.luyuan.crm.member.service.MemberService;
import com.ruijie.components.security.model.AppUser;
import com.ruijie.foundation.security.AppUserContext;
import com.ruijie.web.jsf.action.BaseAction;

@Component("memberIntegralReceivedAction")
@Scope("view")
public class MemberIntegralReceivedAction extends BaseAction implements InitializingBean {

    @Resource(name = "memberService")
    private MemberService memberService;

    @Resource(name = "memberIntegralReceivedService")
    private MemberIntegralReceivedService memberIntegralReceivedService;

    // 添加或编辑模型
    private Member member = null;

    private int integral = 0;

    public int getIntegral() {
        return integral;
    }

    public Member getMember() {
        return member;
    }

    public void updateUser() {
        memberService.updateMember(member);

        addGlobalI18nMessage("crud_update_success_msg");
    }

    public void receiveMemberIntegral() {
        List<MemberIntegralReceived> memberIntegralReceiveds = memberIntegralReceivedService.receiveMemberIntegral(
                member, "领取活动积分");
        if (memberIntegralReceiveds == null || memberIntegralReceiveds.isEmpty()) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "您没有未领取的积分！", null));
            return;
        }

        String message = "";
        for (MemberIntegralReceived memberIntegralReceived : memberIntegralReceiveds) {
            message = memberIntegralReceived.getDescription();
        }
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "感谢你的参与，已经领取" + integral + "积分!", null));
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "活动说明：" + message, null));

        integral = 0;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        member = memberService.getByAccount((AppUser) AppUserContext.getCurrentUser());
        integral = memberIntegralReceivedService.sumReceiveMemberIntegral(member);
    }
}
